/**
 * Created by Administrator on 2017/5/3.
 */
import React from 'react';
import {browserHistory} from 'react-router';
import { Form, Button, Input, Icon, message, Alert,Select } from 'antd';
import './index.less';
import $ from 'jquery';
import config from './components/config/config';
const token = sessionStorage.getItem('token');
const allRouter=config.router;
const InputGroup = Input.Group;
const Option = Select.Option;
const FormItem = Form.Item;
//使用antd-Form构建登录表单
class LoginForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            storeList:[],//门店列表
        }
    }
    componentWillMount(){
        this.getStoreList();
    }
    componentDidMount(){
        //开始执行一次随机生成验证码
        this.captcha();
    }
    //随机生成验证码
    captcha() {
        const form = this.props.form;
        let expression = '';
        const codeNormal = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; //字母库
        for (let i = 0; i < 4; i++) {
            expression = expression + codeNormal[Math.round(Math.random() * (codeNormal.length - 1))]; //随机获取四个字母
        }
        this.setState({
            expression: expression,
            isDisabled: true,
        }, () => {
            if (form.getFieldValue('verifyCode') && this.state.confirmDirty) { //点击更换验证码时，立刻进行输入验证码的表单验证
                form.validateFields(['verifyCode'], { force: true });
            }
        });
    }
    //输入验证码触发的函数
    stepOneGetPhone(e) {
        const form = this.props.form;
       // console.log(!this.props.form.getFieldError('Phone'), !this.props.form.getFieldError('verifyCode'), this.props.form.getFieldValue('verifyCode'))
        setTimeout(() => {
            //console.log(this.props.form.getFieldError('verifyCode'));
            if (!this.props.form.getFieldError('Phone') && !this.props.form.getFieldError('verifyCode') && this.props.form.getFieldValue('verifyCode')) {
                this.setState({
                    isDisabled: false,
                    phoneCode: form.getFieldValue('verifyCode')
                },()=>{
                    if(this.state.phoneCode.toUpperCase()!=this.state.expression.toUpperCase()){
                        this.props.form.setFields({
                            verifyCode: { value: this.state.phoneCode,errors: [new Error('验证码输入错误')]}
                        })
                    }
                })
            } else {
                this.setState({
                    isDisabled: true
                })
            }
        }, 0)
    }
    //提交登录表单
    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            let url=allRouter.patientOrigin+'/login';
            if (!err) {
                if(this.state.phoneCode.toUpperCase()!=this.state.expression.toUpperCase()){
                    this.props.form.setFields({
                        verifyCode: { value: this.state.phoneCode,errors: [new Error('验证码输入错误')]}
                    });
                    return;
                }
                console.log(values);
                $.ajax({
                    url:url,
                    type: "post",
                    async: true,
                    data: {
                        phone: values.userName,
                        password: values.password,
                        storeId:values.storeId,
                    },
                    success: res => {
                       console.log(res);
                        if (res.code === 200) {
                            let url=allRouter.patientOrigin+'/role/list';
                            $.ajax({
                                url:url,
                                type:'GET',
                                headers: { Authorization: 'Bearer '+res.token},
                                success:res1=>{
                                    if(res1.code===200){
                                        const rolesList = res1.roles;
                                        rolesList.map(value=>{
                                            if(value._id===res.Userinfo.role){
                                                res.Userinfo.roleName=value.name;
                                                //判断是否是ie，ie不支持session
                                                if (window.sessionStorage) {
                                                    sessionStorage.setItem("UserInfo", JSON.stringify(res.Userinfo));
                                                    sessionStorage.setItem('token', res.token); //token
                                                } else {
                                                    localStorage.setItem("UserInfo", JSON.stringify(res.Userinfo));
                                                    localStorage.setItem('token', res.token); //token
                                                }
                                                message.success('登录成功，即将跳转到首页', 1, ()=>{browserHistory.push({pathname:'/',state:res.token});});
                                                return;
                                            }
                                        })
                                    }else{
                                        message.error('登录失败，请重新操作', 2);
                                    }
                                },
                                error:err=>{
                                    message.config({ top: 80, });
                                    message.error('登录失败，请重新操作', 2);
                                }
                            })
                        } else {
                            message.error(res.mes, 2);
                            // if (res.code === 202) {
                            //     this.props.form.setFields({
                            //         userName: { value: values.userName, errors: [new Error(res.mes)] },
                            //         password: { value: values.password, errors: '' }
                            //     })
                            // } else {
                            //     this.props.form.setFields({
                            //         userName: { value: values.userName, errors: '' },
                            //         password: { value: values.password, errors: [new Error(res.mes)] }
                            //     })
                            // }

                        }
                    }
                });
            }
        });
    }
    //获取门店列表
    getStoreList() {
        let url=allRouter.patientOrigin+'/cmmuseumlist/initlist';
        //console.log(url);
        $.ajax({
            url:url,
            type: "GET",
            async: true,
            success:data=>{
                console.log(data);
                if(data.code===200){
                    this.setState({
                        storeList:data.cmmuseums
                    })
                }else{
                    console.log("获取门店列表出错");
                }
            },
            error:err=>{
                console.log(err);
            }
        });
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form onSubmit={this.handleSubmit.bind(this)}>
                <div className="center buyoca">
                    <div className="login login1">
                        <div className="login2">
                            <span className="lwef"><img src={require('./images/logo1.png')}/> </span>
                            <FormItem className="formItem loginInput" label='用户名:' style={{ color: '#333' }}>
                                {getFieldDecorator('userName', {
                                    rules: [{ required: true, whitespace: true, pattern: /^(1[34578]\d{9})$/, message: '必须为11位手机号'}],
                                })(
                                    <Input prefix={<Icon type="user" style={{ fontSize: 14 }} />} placeholder="输入手机号" name="userName" />
                                )}
                            </FormItem>
                            <FormItem className="formItem loginInput" label='密码:' style={{ color: '#333' }}>
                                {getFieldDecorator('password', {
                                    rules: [
                                        { required: true, message: '密码输入错误' },
                                        {  min: 6,  message: '密码不能低于6位数' },
                                        ],
                                })(
                                    <Input prefix={<Icon type="lock" style={{ fontSize: 14 }} />} type="password" placeholder="密码" />
                                )}
                            </FormItem>
                            <FormItem className="formItem loginInput" label='门店:' style={{ color: '#333' }}>
                                {getFieldDecorator('storeId', {
                                    rules: [
                                        { required: true, message: '请选择门店' },
                                    ],
                                })(
                                    <Select placeholder="请选择门店">
                                        {this.state.storeList.map(item=><Option value={item._id} key={item._id}>{item.name}</Option>)}
                                    </Select>
                                )}
                            </FormItem>
                            <div className="mt10 rgre" style={{ marginBottom: 10 }}>
                                <FormItem className="formItem yzmInput " label='验证码:'>
                                    {getFieldDecorator('verifyCode', {
                                        rules: [{ required: true,  message: '请输入验证码'}],
                                    })(
                                        <Input className="rgre1" placeholder="输入验证码" name='verifyCode' onKeyUp={this.stepOneGetPhone.bind(this)} />
                                    )}
                                    <div className="yzm">{this.state.expression}</div>
                                    <a href="javascript:void(0);" className="ghyzm" onClick={this.captcha.bind(this)}>看不清？换一张</a>
                                </FormItem>
                            </div>
                            <div className="afcrbb">
                                <FormItem className="formItem">
                                    <Button type="primary" htmlType="submit" className="btn">登 录</Button>
                                </FormItem>
                            </div>
                        </div>
                    </div>
                </div>
            </Form>
        );
    }
}
const WrappedNormalLoginForm = Form.create()(LoginForm);

class Login extends React.Component {
    constructor(props) {
        super(props);
        this.state = {

        }
    }
    render() {
        return <div className="login">
            <WrappedNormalLoginForm />
            <div className="foot">
                <p className="txt">版权所有 @湖南橘色科技有限责任公司</p>
                <p className="txt">湘ICP备14013922号</p>
            </div>
        </div>

    }
}

export default Login;